package ca.uwindsor.cs.deepweb.estimation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.search.Hits;

public class DocumentFrequencyAnalyzer {

	/**
	 * The name of the Filed for query
	 */
	protected String string_FieldName;

	protected ArrayList<Vector<Object>> listdocumentfrequency;
	
	protected HashMap<String, Integer> map_documentfrequency;
	
	protected ArrayList<Vector<Integer>> listfrequency;
	
	protected HashMap<Integer, Integer> map_frequency;
	
	private static int length;
	
	private static int index;
	
	private String id;
	
	public DocumentFrequencyAnalyzer() {
		listdocumentfrequency = new ArrayList<Vector<Object>>();
		listfrequency = new ArrayList<Vector<Integer>>();
		map_documentfrequency = new HashMap<String, Integer>(1000);
		map_frequency = new HashMap<Integer, Integer>(2);
	}

	public DocumentFrequencyAnalyzer(String idFieldName) {
		this();
		string_FieldName = idFieldName;
	}

	public void addHits(Hits hits) {
		try {
//			int index;
			length = hits.length();
			for (index = 0; index < length; index++) {
				id = hits.doc(index).get(string_FieldName);
				addID(id);
			}
		} catch (CorruptIndexException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void addID(String id){
		if(!map_documentfrequency.containsKey(id)){
			map_documentfrequency.put(id, 1);
		}else{
			int i = map_documentfrequency.get(id);
			i++;
			map_documentfrequency.put(id, i);
		}
	}
	
	public HashMap<Integer, Integer> getFrequencyMap(){
		Set<Entry<String, Integer>> s = map_documentfrequency.entrySet();
		for(Entry<String, Integer> e : s){
			int f = e.getValue();
			addFrequency(f);
		}
		return map_frequency;
	}
	
	public HashMap<String, Integer> getDocumentFrequency(){
		return map_documentfrequency;
	}
	
	public void addFrequency(int f){
		if(!map_frequency.containsKey(f)){
			map_frequency.put(f, 1);
		}else{
			int i = map_frequency.get(f);
			i++;
			map_frequency.put(f, i);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DocumentFrequencyAnalyzer dfa = new DocumentFrequencyAnalyzer();
		dfa.addID("abcd");
		dfa.addID("abcd");
		dfa.addID("abc");
		dfa.addID("abcde");
		HashMap<Integer, Integer> fl = dfa.getFrequencyMap();
		Set<Entry<Integer, Integer>> s = fl.entrySet();
		for (Entry<Integer, Integer> e : s){
			System.out.println(e.getKey());
			System.out.println(e.getValue());
		}
	}

}
